/********************
* Get the cohorts for the NY-ON-NSW comparison.
*
* The macro `get_cohorts` finds all records for
* any patient that has a specified procedure code
* as the principal procedure.

*******************/

%let apdc = apdcx;	

/* If no indexes, run this code to create them */
proc datasets library=apdc;
	modify &apdc;
	index create procedure_codeP;
	index create ppn;
quit;

/*********
* get_cohort
*
* indata: the input dataset (APDC)
* outdat: where to put the cohort dataset
* proc_codes: the ACHI procedure codes to search for 
*
*********/
options msglevel=I;
%macro get_cohort (indata, outdata, proc_codes);
proc sql;
	create table temp1 as
	select distinct ppn
	from &indata
	where procedure_codeP in (&proc_codes);

data &outdata(compress=yes);
	length ppn $14;

	if _N_ = 1 then do;
		declare hash ht(dataset: "work.temp1");
		ht.definekey("ppn");
		ht.definedone();
		call missing(ppn);
	end;
	set apdc.apdcx;
	if ht.find() = 0 ;
  format index_date date9.;
  if procedure_codeP in (&proc_codes) then index_flag = 1;
  else index_flag = 0;
  if index_flag = 1 then do;
    if missing(procedure_dateP) then index_date = episode_start_date;
    else index_date = procedure_dateP;
  end;

run;
%mend;